package patrol.mobile.com.mobilepatrol.activity.road_block;

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import patrol.mobile.com.mobilepatrol.DBHelper;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.activity.route_query.RouteActivity;
import patrol.mobile.com.mobilepatrol.activity.route_query.RouteManage;
import patrol.mobile.com.mobilepatrol.activity.route_query.TotalRouteActivity;
import patrol.mobile.com.mobilepatrol.adapter.ImagePickerAdapter;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.Constants;
import patrol.mobile.com.mobilepatrol.utils.DateUtil;
import patrol.mobile.com.mobilepatrol.utils.GlideImageLoader;
import patrol.mobile.com.mobilepatrol.utils.UIHelper;
import patrol.mobile.com.mobilepatrol.widget.dialog.SelectDialog;

/**
 * Created by apple on 18/1/25.
 * 是否可以修改
 *      畅通时间填写修改条件
 *      1 数据未上传过，点击恢复畅通
 *      2 没有畅通时间上传过，点击恢复畅通
 *
 *
 *      是否有畅通时间，数据是否上传
 *      只有点击恢复畅通才能修改畅通时间？
 *      畅通时间只要不上传就能再修改？，上传之后还可以修改吗？
 *
 *      整条数据填写修改条件
 *
 *      1 没有上传，没有畅通时间  随便修改
 *      2 有畅通时间，没有上传    随便修改
 *      3 数据上传过，没有畅通时间 随便修改
 *      4 上传过，且有畅通时间   数据不能再修改
 *
 *
 * 1 新增后修改
 * 3 上传后修改
 * 4 填写完恢复畅通时间后
 *
 *
 * 只要上传过的数据就不能修改
 */

public class EidtBlockActivity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener{

    private ArrayList<ImageItem> selImageList;
    private ImagePickerAdapter adapter;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private int limitSize = 4;

    //（1）标题 ：手动填入，必填
    @BindView(R.id.et_title)
    EditText et_title;


    //（2）路线编码：选择当前登录人员所在的机构管养路线，数据来源于路线查询，上一个功能，格式为：S112(K100+500-K60+600)，必填
    @BindView(R.id.rl_road_code)
    RelativeLayout rl_road_code;

    @BindView(R.id.tv_road_code)
    TextView tv_road_code;

    //  (3) 影响方向：下拉：全幅，下行，上行，双向，必填
    @BindView(R.id.s_o)
    Spinner s_o;


    // (4) 路段状态：下拉：封闭，半封闭，预警，必填
    @BindView(R.id.s_s)
    Spinner s_s;

    //(5) 点线区分不要了。
    //(6) 事件时间，默认当前时间，可选择，具体到分秒。必填
    @BindView(R.id.rl_time)
    RelativeLayout rl_time;
    @BindView(R.id.tv_time)
    TextView tv_time;



    //(7) 起点名称，手动输入，必填
    @BindView(R.id.et_start_name)
    EditText et_start_name;

    //(8) 终点名称，手动输入
    @BindView(R.id.et_end_name)
    EditText et_end_name;
    // (9) 起点桩号，手动输入，必填
    @BindView(R.id.et_startpotkm)
    EditText et_startpotkm;

    @BindView(R.id.et_startpotm)
    EditText et_startpotm;

    @BindView(R.id.et_endpotkm)
    EditText et_endpotkm;

    @BindView(R.id.et_endpotm)
    EditText et_endpotm;
//    //(10) 终点桩号，手动输入，必填
//    @BindView(R.id.et_end_pot)
//    EditText et_end_pot;
    //(11) 管养单位，当前用户登录单位，单位id也要保存
    @BindView(R.id.tv_org)
    TextView tv_org;


    // (11) 预计恢复畅通时间，选择时间。
    @BindView(R.id.rl_pretime)
    RelativeLayout rl_pretime;
    @BindView(R.id.tv_pretime)
    TextView tv_pretime;


    // (12) 恢复畅通时间，新增时不能修改，只有恢复畅通的时候才可以修改。
    @BindView(R.id.rl_retime)
    RelativeLayout rl_retime;
    @BindView(R.id.tv_retime)
    TextView tv_retime;
    // (11) 详细说明，手动输入，多行，必填
    @BindView(R.id.et_detail)
    EditText et_detail;
    //(12) 绕行方案：手动输入，必填
    @BindView(R.id.et_pass_plan)
    EditText et_pass_plan;
    //(13) 上传照片：最多四张。
    @BindView(R.id.recyclerView)
    RecyclerView rv;

    @BindView(R.id.bt)
    Button bt;
    private TimePickerView pvTime,pvPreTime,pvReTime;
    private AssetTongzuxinxi mData;

    //是否点击恢复畅通，true是
    private boolean isClickRecover;
    private boolean isRetimeUp = false;



    //是否上报 已上报
    private String reportingStatus;



    //进入该页面有三种情况//新增，修改item，修改retime
    public int ui_role;
    private DBHelper db;
    private RouteManage routeManage;
    private String title;
    private String road_code;
    private String affect_direction;
    private String road_status;
    private String time;
    private String start_name;
    private String end_name;
    private String start_potk;
    private String start_potm;
    private String end_potk;
    private String end_potm;
    private String orgName;
    private String pretime;
    private String retime;
    private String detail;
    private String pass_plan;
    private String imgs;


    @Override
    protected int attachLayoutRes() {
        return R.layout.edit_block;
    }

    @Override
    public void setListener() {
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                title = CommonUtil.getText(et_title);
                road_code = CommonUtil.getText(tv_road_code);
                affect_direction = s_o.getSelectedItem().toString();
                road_status = s_s.getSelectedItem().toString();
                time = CommonUtil.getText(tv_time);
                start_name = CommonUtil.getText(et_start_name);
                end_name = CommonUtil.getText(et_end_name);
                start_potk = CommonUtil.getText(et_startpotkm);
                start_potm = CommonUtil.getText(et_startpotm);
                end_potk = CommonUtil.getText(et_endpotkm);
                end_potm = CommonUtil.getText(et_endpotm);
                orgName = CommonUtil.getText(tv_org);
                pretime = CommonUtil.getText(tv_pretime);
                retime = CommonUtil.getText(tv_retime);
                detail = CommonUtil.getText(et_detail);
                pass_plan = CommonUtil.getText(et_pass_plan);
                imgs = "";
                if (selImageList!=null&&selImageList.size()>0){
                    for (int i=0;i<selImageList.size();i++){
                        imgs = imgs+selImageList.get(i).path+",";
                    }
                }
                switch (ui_role){
                    case 1:
                        //新增
                        insertData();
                        break;
                    case 2:
                        alterItem();
                        break;
                    case 3:
                        alterTime();
                        break;
                }
            }
        });
        rl_road_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent;
                if (UserManager.getUser().orgtype.equals("总局")){
                     intent = new Intent(EidtBlockActivity.this,TotalRouteActivity.class);
                     intent.putExtra("from",2);
                     startActivityForResult(intent,0);
                }else{
                    intent = new Intent(EidtBlockActivity.this,RouteActivity.class);
                    intent.putExtra("from",2);
                    startActivityForResult(intent,1);
                }
                CommonUtil.openNewActivityAnim(EidtBlockActivity.this,false);
            }
        });
        rl_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pvTime.show();
            }
        });
        rl_pretime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pvPreTime.show();
            }
        });
        rl_retime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pvReTime.show();
            }
        });

    }

    private void alterTime() {
        AssetTongzuxinxi a = new AssetTongzuxinxi();
        a.id = mData.id;
        a.status = road_status;
        a.blockTime = time;
        a.routeCoding = road_code;
        a.routeId = mData.routeId;
        a.startLocation = start_name;
        a.endLocation = end_name;
        a.description = detail;
        a.recoveryTime = pretime;
        a.plan = pass_plan;
        a.startPotKm = Long.valueOf(start_potk);
        a.startPotM = Long.valueOf(start_potm);
        a.endPotKm = Long.valueOf(end_potk);
        a.endPotM = Long.valueOf(end_potm);
        a.upDown = affect_direction;
        a.title = title;
        a.orgId = mData.orgId;
        a.orgName = mData.orgName;
        a.smoothreCoveryTime = retime;
        a.reportingStatus = "未上报";
        a.isRetimeUp = 0;
        a.isDataUp = mData.isDataUp;
        a.imgs = mData.imgs;

        db.updateBlockData(a);
        showToast("修改数据成功");
        CommonUtil.exitActivityAndBackAnim(this,true);
    }

    private void alterItem() {
        AssetTongzuxinxi a = new AssetTongzuxinxi();
        a.id = mData.id;
        a.status = road_status;
        a.blockTime = time;
        a.routeCoding = road_code;
        if (routeManage!=null){
            a.routeId = routeManage.id;
        }else{
            a.routeId = mData.routeId;
        }
        a.startLocation = start_name;
        a.endLocation = end_name;
        a.description = detail;
        a.recoveryTime = pretime;
        a.plan = pass_plan;
        a.startPotKm = Long.valueOf(start_potk);
        a.startPotM = Long.valueOf(start_potm);
        a.endPotKm = Long.valueOf(end_potk);
        a.endPotM = Long.valueOf(end_potm);
        a.upDown = affect_direction;
        a.title = title;
        if (routeManage!=null){
            a.orgId = routeManage.orgId;
            a.orgName = routeManage.orgName;
        }else{
            a.orgId = mData.orgId;
            a.orgName = mData.orgName;
        }
        a.smoothreCoveryTime = retime;
        a.reportingStatus = "未上报";
        a.isDataUp = 0;
        a.isRetimeUp = mData.isRetimeUp;
        a.imgs = imgs;
        db.updateBlockData(a);
        showToast("修改数据成功");
        CommonUtil.exitActivityAndBackAnim(this,true);
    }

    private void insertData() {

        AssetTongzuxinxi a = new AssetTongzuxinxi();
        a.id = CommonUtil.getUUID();
        a.status = road_status;
        a.blockTime = time;
        a.routeCoding = road_code;
        a.routeId = routeManage.id;
        a.startLocation = start_name;
        a.endLocation = end_name;
        a.description = detail;
        a.recoveryTime = pretime;
        a.plan = pass_plan;
        a.startPotKm = Long.valueOf(start_potk);
        a.startPotM = Long.valueOf(start_potm);
        a.endPotKm = Long.valueOf(end_potk);
        a.endPotM = Long.valueOf(end_potm);
        a.upDown = affect_direction;
        a.title = title;
        a.orgId = routeManage.orgId;
        a.orgName = orgName;
        a.smoothreCoveryTime = retime;
        a.reportingStatus = "未上报";
        a.isRetimeUp = 0;
        a.isDataUp = 0;
        a.imgs = imgs;

        db.insertAssetTong(a);
        showToast("插入数据成功");
        CommonUtil.exitActivityAndBackAnim(this,true);
    }

    @Override
    public void initData() {
        super.initData();
        //intent
        mData = (AssetTongzuxinxi) getIntent().getSerializableExtra(UIHelper.ATongzuxinxi);
        ui_role = getIntent().getIntExtra("ui_role",-1);
        //初始化布局
        switch (ui_role){
            //新增
            case 1:
                setReTimeEnable(false);
                break;
            //修改
            case 2:
                setReTimeEnable(false);
                if (mData.isDataUp==1){
                    bt.setVisibility(View.GONE);
                    setItemEnable(false);
                }else{
                    setItemEnable(true);
                }
                break;
            //修改时间
            case 3:
                if (mData.isRetimeUp==1){
                    setItemEnable(false);
                    setReTimeEnable(false);
                    bt.setVisibility(View.GONE);
                }else{
                    setReTimeEnable(true);
                    setItemEnable(false);
                }
                break;
        }
        //初始化赋值
//        tv_org.setText(UserManager.getUser().bmname);
        if (mData==null){
            tv_time.setText(DateUtil.getCurrentDate(Constants.formatdate));




        }else{
            et_title.setText(mData.title);
            tv_road_code.setText(mData.routeCoding);
            selectedItem(s_o,mData.upDown);
            selectedItem(s_s,mData.status);
            tv_time.setText(mData.blockTime);
            et_start_name.setText(mData.startLocation);
            et_end_name.setText(mData.endLocation);
            et_startpotkm.setText(mData.startPotKm+"");
            et_startpotm.setText(mData.startPotM+"");
            et_endpotkm.setText(mData.endPotKm+"");
            et_endpotm.setText(mData.endPotM+"");
            tv_pretime.setText(mData.recoveryTime);
            tv_retime.setText(mData.smoothreCoveryTime);
            et_detail.setText(mData.description);
            et_pass_plan.setText(mData.plan);
            tv_org.setText(mData.orgName);
            //
            String pn = mData.imgs;
            if (!pn.equals("")){
                String[] imgs = pn.split(",");
                List<ImageItem> lastImgs = new ArrayList<>();
                for (int i=0;i<imgs.length;i++){
                    ImageItem item = new ImageItem();
                    item.path = imgs[i];
                    lastImgs.add(item);
                }
                adapter.setImages(lastImgs);
            }

        }


    }

    @Override
    public void initView() {
        super.initView();
        //时间
        initTime();
        initPic();
        initImagePicker();
        db = new DBHelper(this);

    }

    private void initPic() {
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, limitSize);
        adapter.setOnItemClickListener(this);
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new GridLayoutManager(this, limitSize));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }

    private void initTime() {

       //时间选择器
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                tv_time.setText(DateUtil.convert2String(date, Constants.formatdate));
            }
        })
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。


        //时间选择器
        pvPreTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                tv_pretime.setText(DateUtil.convert2String(date, Constants.formatdate));
            }
        })
                .build();
        pvPreTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。


        //时间选择器
        pvReTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                tv_retime.setText(DateUtil.convert2String(date, Constants.formatdate));
            }
        })
                .build();
        pvReTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。

    }

    @Override
    public void initTitle() {
        super.initTitle();
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(EidtBlockActivity.this,true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("编辑界面");
    }
    ArrayList<ImageItem> images = null;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data!=null) {
            switch (resultCode) {
                case 0:
                    break;
                case 1:
                    routeManage = (RouteManage) data.getSerializableExtra("route");
                    tv_road_code.setText(routeManage.routeCode + " ( " + routeManage.startPot + " - " + routeManage.endPot + " )");
                    tv_org.setText(routeManage.orgName);

                    break;
                case ImagePicker.RESULT_CODE_ITEMS:
                    //添加图片返回
                    if (requestCode == REQUEST_CODE_SELECT) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        if (images != null) {
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case ImagePicker.RESULT_CODE_BACK:
                    //预览图片返回
                    if (requestCode == REQUEST_CODE_PREVIEW) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                        if (images != null) {
                            selImageList.clear();
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
            }
        }
    }
    private void setEnable(boolean b){
        if (b){

        }else{

        }
    }
    //恢复畅通时间是否可以修改，1 是否是点击恢复畅通，2 是否上传过
    private void setReTimeEnable(boolean b){
//        if (!b){
//            tv_retime.setBackground(getResources().getDrawable(R.drawable.bg_et2));
//        }else{
//            tv_retime.setBackground(getResources().getDrawable(R.drawable.bg_et4));
//        }
        rl_retime.setEnabled(b);
        tv_retime.setEnabled(b);
    }
    private void setItemEnable(boolean b){
//        if (b){
//            et_title.setBackground(getResources().getDrawable(R.drawable.bg_et4));
//            tv_road_code.setBackground(getResources().getDrawable(R.drawable.bg_et4));
//            tv_time.setBackground(getResources().getDrawable(R.drawable.bg_et4));
//            et_start_name.setBackground(getResources().getDrawable(R.drawable.bg_et4));
//            et_start_pot.setBackground(getResources().getDrawable(R.drawable.bg_et4));
//        }else{
//            et_title.setBackground(getResources().getDrawable(R.drawable.bg_et2));
//            tv_road_code.setBackground(getResources().getDrawable(R.drawable.bg_et2));
//            tv_time.setBackground(getResources().getDrawable(R.drawable.bg_et2));
//            et_start_name.setBackground(getResources().getDrawable(R.drawable.bg_et2));
//            et_start_pot.setBackground(getResources().getDrawable(R.drawable.bg_et4));
//        }
        et_title.setEnabled(b);
        rl_road_code.setEnabled(b);
        tv_road_code.setEnabled(b);
        s_o.setEnabled(b);
        s_s.setEnabled(b);
        rl_time.setEnabled(b);
        tv_time.setEnabled(b);
        et_start_name.setEnabled(b);
        et_startpotkm.setEnabled(b);
        et_startpotm.setEnabled(b);
        et_endpotkm.setEnabled(b);
        et_endpotm.setEnabled(b);
        et_end_name.setEnabled(b);
        rl_pretime.setEnabled(b);
        tv_pretime.setEnabled(b);
        et_detail.setEnabled(b);
        et_pass_plan.setEnabled(b);
        if (!b){
            adapter.setOnItemClickListener(null);
        }


    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                /**
                                 * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
                                 *
                                 * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
                                 *
                                 * 如果实在有所需要，请直接下载源码引用。
                                 */
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent = new Intent(EidtBlockActivity.this, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent1 = new Intent(EidtBlockActivity.this, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                break;
                            default:
                                break;
                        }

                    }
                }, names);


                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }
    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
//        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setMultiMode(true);
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(limitSize);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }
}
